use std::{env, fs};

use regex::Regex;

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() != 3 {
        panic!(
            "Expected args: stores.rs and output paths, got: {:?}",
            args.iter().skip(1).collect::<Vec<&String>>()
        );
    }
    let stores_rs_filename = &args[1];
    let output_config = &args[2];
    let stores_rs = String::from_utf8(fs::read(stores_rs_filename).unwrap()).unwrap();

    let json_start = Regex::new(r"///\s+```json").unwrap();
    let block_end = Regex::new(r"///\s+```").unwrap();

    let mut blocks: Vec<String> = vec![];

    for block in json_start.captures_iter(&stores_rs) {
        let start_marker = block.get(0).unwrap().end();
        let end_match = block_end.find(&stores_rs[start_marker..]).unwrap();
        let end_marker =end_match.start();
        let contents = &stores_rs[start_marker..(start_marker+end_marker)].split("\n").map(|line| line.replacen("///", "", 1)).collect::<Vec<String>>().join("\n");
        blocks.push(contents.trim().to_string());
    }

    let mut output = String::from("// Generated by generate-stores-config from stores.rs comments for testing
{
  servers: [],
  stores: [
");

    for (index, contents) in blocks.iter().enumerate() {
        let more_output = format!(r#"    {{
      name: "{index}",
      {contents}
    }},
"#);
        output.push_str(&more_output);
    }
    output.push_str("]}\n");
    fs::write(output_config, output).unwrap();
}
